package com.saudidentalapp;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.saudiapp.webservice.Constants;
import com.saudiapp.webservice.Responce;
import com.saudiapp.webservice.Utilities;
import com.saudiapp.webservice.Utilities.DialogListener;
import com.saudiapp.webservice.WebServiceManager;
import com.saudiapp.webservice.WebServiceManager.WebServiceListener;
import com.saudidentalapp.datamodels.CECourse;
import com.saudidentalapp.datamodels.Program;
import com.saudidentalapp.datamodels.ProgramDay;
import com.saudidentalapp.datamodels.ProgramMinutes;

public class ProgramActivity extends Activity implements WebServiceListener,OnItemClickListener
{
	ListView lstPrograms;
	Utilities utilities;
	LinearLayout top_menu_layout;
	TextView txtDay,txtDate,txtDataStatus;	
	
	 @Override
	protected void onCreate(Bundle savedInstanceState) 
	 {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_programs);
		lstPrograms=(ListView)findViewById(R.id.xlstPrograms);
		setView();
	}
	 
	private void setView()
	{
		utilities=Utilities.getInstance(ProgramActivity.this);
		utilities.showProgreessDialog();
		if(utilities.haveNetworkConnection())
		{
			WebServiceManager webServiceManager=new WebServiceManager(this);
			webServiceManager.setonWebServiceListener(this);
			//webServiceManager.getProgramsInformation();
			webServiceManager.getProgramDays();
		}
		else
		{
		utilities.dismiss();
		utilities.showToast(Constants.INTERNET_NOT_AVAILABELE);
		}
		
		top_menu_layout=(LinearLayout)findViewById(R.id.xtop_menu_layout);
		txtDay=(TextView)findViewById(R.id.textViewDay);
		txtDate=(TextView)findViewById(R.id.textViewDate);	
		txtDataStatus=(TextView)findViewById(R.id.xtxtDataStatus);	
		txtDataStatus.setVisibility(View.GONE);
		final Activity activity=this;
		ImageView imgBack=(ImageView)findViewById(R.id.xbtnVwBack);
		imgBack.setOnClickListener(new OnClickListener() 
		{
			
			@Override
			public void onClick(View arg0) 
			{
				finish();
				startActivity(new Intent(activity,TabActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
				
			}
		});
		
		
		
		
	}

	
	ArrayList<ProgramDay> programDays;
	
	int dayID;
	int dayIndex;
	Button btnPreviousView[];
	@SuppressWarnings("unchecked")
	@Override
	public void onProcesCompleted(final int requestId, Object Data) 
	{	
		utilities.dismiss();
		ArrayList<ProgramMinutes> programMinutes;
		
		if(requestId==3)
		{
			 programDays=((ArrayList<ProgramDay>)((Responce)Data).getResponceData());			
			 btnPreviousView=new Button[programDays.size()+1];
			for(int i=0;i<=programDays.size();i++)
			{
				Button btnDy=new Button(ProgramActivity.this);				
				if(i<programDays.size())
				{					
					
					btnDy.setText(""+programDays.get(i).getTitle());				
				}
				else
				{				
			
					btnDy.setText("Ce-Courses");
					btnDy.setTag(i);
					
				}
				btnDy.setTextColor(Color.WHITE);
				btnDy.setBackgroundResource(R.drawable.week_bg);
			
				LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT);
				//btnDy.setPadding(5, 5, 5, 5);
				layoutParams.setMargins(0, 0, 2, 0);
				btnDy.setLayoutParams(layoutParams);					
				//layoutParams.weight=1F;
				btnDy.setTag(i);	
				btnPreviousView[i]=btnDy;
				btnDy.setOnClickListener(new OnClickListener() 
				{
					
					@Override
					public void onClick(View v) 
					{
						if(v.getTag()!=null)
						{
							for(int i=0;i<btnPreviousView.length;i++)
								btnPreviousView[i].setBackgroundResource(R.drawable.week_bg);
							
							dayID=Integer.parseInt(v.getTag().toString());
							
							btnPreviousView[dayID].setBackgroundResource(R.drawable.week_bg_sel);
							utilities=Utilities.getInstance(ProgramActivity.this);
							utilities.showProgreessDialog();
							if(dayID!=programDays.size())
							{			
								WebServiceManager webServiceManager=new WebServiceManager(ProgramActivity.this);
								webServiceManager.setonWebServiceListener(ProgramActivity.this);	
								webServiceManager.getMinutes(Integer.parseInt(v.getTag().toString())+1);
							}
							else
							{
								WebServiceManager webServiceManager=new WebServiceManager(ProgramActivity.this);
								webServiceManager.setonWebServiceListener(ProgramActivity.this);	
								webServiceManager.getCEcourses();
							}
						}						
					}
				});
				
				top_menu_layout.addView(btnDy, i);
			}		
			//show the default for day 1
			
			//dayID=Integer.parseInt(v.getTag().toString());
			WebServiceManager webServiceManager=new WebServiceManager(ProgramActivity.this);
			webServiceManager.setonWebServiceListener(ProgramActivity.this);
			webServiceManager.getMinutes(1);
			dayID=0;
			btnPreviousView[dayID].setBackgroundResource(R.drawable.week_bg_sel);
		}		
		else if(requestId==4)
		{
			
			try {
				if(((Responce)Data).getResult_Type()==Constants.DataPresent)
				{
				txtDataStatus.setVisibility(View.GONE);
				txtDay.setText(""+programDays.get(dayID).getTitle());				
				txtDate.setText(convertToDate(""+programDays.get(dayID).getDate()));
				txtDay.setVisibility(View.VISIBLE);
				txtDate.setVisibility(View.VISIBLE);
				lstPrograms.setVisibility(View.VISIBLE);
				//programMinutes=((ArrayList<ProgramMinutes>)((Responce)Data).getResponceData());			 
				// MinutesAdapter adapter=new MinutesAdapter(ProgramActivity.this, R.layout.custom_minutes_row, programMinutes);
				 
				programMinutes=((ArrayList<ProgramMinutes>)((Responce)Data).getResponceData());			 
				ProgrameAdapter adapter=new ProgrameAdapter(ProgramActivity.this, R.layout.custom_programs_row, programMinutes,convertToDate(""+programDays.get(dayID).getDate()));
				
				 lstPrograms.setAdapter(adapter);
				}
				else
				{
					lstPrograms.setVisibility(View.GONE);
					txtDataStatus.setVisibility(View.VISIBLE);
					txtDay.setVisibility(View.GONE);
					txtDate.setVisibility(View.GONE);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 
		}
		else if(requestId==5)
		{
			try {
				if(((Responce)Data).getResult_Type()==Constants.DataPresent)
				{
					ArrayList<CECourse> ceCourses=((ArrayList<CECourse>)((Responce)Data).getResponceData());	
					CEAdapter adapter=new CEAdapter(ProgramActivity.this, R.layout.custom_ce_courses,ceCourses);
					
					lstPrograms.setAdapter(adapter);
					lstPrograms.setVisibility(View.VISIBLE);
					txtDataStatus.setVisibility(View.GONE);
					txtDay.setVisibility(View.GONE);
					txtDate.setVisibility(View.GONE);
					
					lstPrograms.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> arg0, View arg1,	int position, long arg3) 
						{
							if(requestId==5)
							{
								CECourse ceCourse=(CECourse)lstPrograms.getAdapter().getItem(position);
								
								if(!ceCourse.getPdfFile().equalsIgnoreCase("") && !ceCourse.getPdfFile().equalsIgnoreCase("#"))
								{
									Intent intentWebSite=new Intent(ProgramActivity.this, WebActivity.class);	
									intentWebSite.putExtra("url", "http://docs.google.com/viewer?url="+ceCourse.getPdfFile());			
									startActivity(intentWebSite);
								}
								else
								{
									utilities.showToast(Constants.DATA_NOT_AVAILABELE);
								}
								
								
							}
						}
					});
					
				}
				else
				{
					lstPrograms.setVisibility(View.GONE);
					txtDataStatus.setVisibility(View.VISIBLE);
					txtDay.setVisibility(View.GONE);
					txtDate.setVisibility(View.GONE);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}		
			
	}
	
	
	

	@Override
	public void onErrorOccured(int requestId) 
	{
		utilities.dismiss();	
		utilities.showToast(Constants.ERROR_MESSAGE);
		
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) 
	{
		
		final Program program=(Program)arg0.getAdapter().getItem(position);	
		
		if(!isProgramInList(program))
		{
			utilities.showYesNoDialog("Do you want to add this program to schedule?","Add","Cancel");
			utilities.setDialogListener(new DialogListener() {
				
				@Override
				public void OnYesButtonClicked() 
				{
					Constants.MySchedules.add(program);
					utilities.showToast("Program successfully added to schedules..");
					
				}
				
				@Override
				public void OnNoButtonClicked() {
					// TODO Auto-generated method stub
					
				}
			});
		}
		
	}
	
	boolean isProgramInList(Program program)
	{
		boolean result=false;
		for(int i=0;i<Constants.MySchedules.size();i++)
		{
			if(Constants.MySchedules.get(i).getID()==program.getID())
			{
				result=true;
				break;
			}
			else
			{
				result=false;
			}
		}
		
		return result;
	}
	
	
	
	public String convertToDate(String tempDate)
	{
		String ResultDate = null;
		String strDay=tempDate.substring(tempDate.length()-2, tempDate.length());
		String strMonth=tempDate.substring(tempDate.length()-4, tempDate.length()-2);
		String strYear=tempDate.substring(0, 4);
		
		switch (Integer.parseInt(strMonth)) 
		{
			case 1:
				ResultDate=strDay+" January "+ strYear;
				break;
			case 2:
				ResultDate=strDay+" February "+ strYear;
				break;
			case 3:
				ResultDate=strDay+" March "+ strYear;
				break;
			case 4:
				ResultDate=strDay+" April "+ strYear;
				break;
			case 5:
				ResultDate=strDay+" May "+ strYear;
				break;
			case 6:
				ResultDate=strDay+" June "+ strYear;
				break;
			case 7:
				ResultDate=strDay+" July "+ strYear;
				break;
			case 8:
				ResultDate=strDay+" August "+ strYear;
				break;					
			case 9:
				ResultDate=strDay+" September "+ strYear;
				break;
			case 10:
				ResultDate=strDay+" October "+ strYear;
				break;
			case 11:
				ResultDate=strDay+" November "+ strYear;
				break;
			case 12:
				ResultDate=strDay+" December "+ strYear;
				break;
	
			default:
				break;
		}
		
		return ResultDate;
		
		
	}
	
	 
	
	
	
	
	public class CEAdapter extends ArrayAdapter<CECourse>
	{

		Context context;
	    int layoutResourceId;    
	    ArrayList<CECourse>data;	
	    private LayoutInflater inflater=null;
		public CEAdapter(Context context, int resource, List<CECourse> objects) 
		{
			super(context, resource, objects);
			 this.layoutResourceId = resource;
		        this.context = context;
		        this.data = (ArrayList<CECourse>) objects;
		        inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		        
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) 
		{
			View row = convertView;
			Holder holder = null;
	       
	        if(row == null)
	        {        	
	            row = inflater.inflate(layoutResourceId, parent, false);	           
	            holder = new Holder();	         
	            holder.txtTitle = (TextView)row.findViewById(R.id.xtxtTitle);	               
	            row.setTag(holder);
	        }
	        else
	        {
	            holder = (Holder)row.getTag();
	        }
	       
	        CECourse ceCourse = getItem(position);	       
	        holder.txtTitle.setText(ceCourse.getName());	      
	       
	        return row;
	    }   
	    
	}
	static class Holder
    {  
        TextView txtTitle;       
    }

}
